package cse474_MultiThreadedHTTPServer.Environment;

import java.io.IOException;
import java.io.PrintStream;

public class HtmlResponse {
	private CustomURI cUri;
	private String response = "";
	private final String EOL = "\r\n";
	private int length; 
	private int responseConstant;
	private String responseHeader = "";
	public HtmlResponse(CustomURI cUri){
		this.cUri = cUri;
		createResponse();
	}
	private void createResponse() {
		if(cUri.getFileSize() == -1)
		{
			responseConstant = HttpConstants.HTTP_FORBIDDEN;
			cUri.setFileSize(0);
		}else if(cUri.getFileSize() > 20000) 
		{
			responseConstant = HttpConstants.HTTP_BAD_REQUEST;
			cUri.setFileSize(20000);
		}else if(cUri.getFileSize() < 100)
		{
			responseConstant = HttpConstants.HTTP_BAD_REQUEST;
			cUri.setFileSize(100);
		}else{
			responseConstant = HttpConstants.HTTP_OK;
		}
		
		length = 69 + (""+cUri.getFileSize()).length();
		response += "<HTML>";
		response += "<HEAD>";
		response += "<TITLE>";
		response += "I am " +  cUri.getFileSize() + "bytes long";
		response += "</TITLE>";
		response += "</HEAD>";
		response += "<BODY>";
		for(int i = 0; i < cUri.getFileSize() - length ; i++) response += "X";
		response += "</BODY>";
		response += "</HTML>";
	}
	public void getResponse(PrintStream ps)  {
		String responseText = "";
			try {
				switch(responseConstant) {
					case HttpConstants.HTTP_BAD_REQUEST:
					{
						responseText =  " INVALID SIZE";
						break;
					}
					case HttpConstants.HTTP_FORBIDDEN:
					{
						responseText = " INVALID REQUEST";
						break;
					}
					case HttpConstants.HTTP_OK:
					{
						responseText = " OK";
						break;
					}
				}
				ps.print(("HTTP/1.0 " + responseConstant + responseText));
				responseHeader += "HTTP/1.0 " + responseConstant + responseText + "\n";
				ps.write((EOL.getBytes()));
				ps.print(("Content-length: " + cUri.getFileSize()));
				responseHeader += "Content-length: " + cUri.getFileSize() +"\n";
				ps.write((EOL).getBytes());
				ps.print(("Content-type: text/html"));
				responseHeader += "Content-type: text/html" +"\n";
				ps.write((EOL).getBytes());
				ps.write((EOL).getBytes());
				ps.print((response));
				ps.close();
			} catch (IOException e) {
				System.err.println("asd2");
			}
	}
	public String getResponseText() {
		return this.response;
	}
	
	public String getResponseHeader()
	{
		return this.responseHeader;
	}
}
